//
//  ComplaintBusinessViewConroller.m
//  PigMarket
//
//  Created by 张敬 on 2019/7/22.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "MeatComplaintViewConroller.h"
#import "MeatComplationSuccessViewController.h"

#import "MeatComplaintCustomCell.h"
#import "MeatComplaintIphoneCell.h"

#import "MeatComplaintModel.h"


@interface MeatComplaintViewConroller()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UIView *tipView; //提示
@property (nonatomic, strong) UIView *footer;
@property (strong, nonatomic) UIImagePickerController *imagePicker;
@property (nonatomic, strong) UITapGestureRecognizer *tap;
@property (nonatomic, strong) MeatComplaintModel *model;

@end


@implementation MeatComplaintViewConroller

#pragma mark - view life cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpView];
}

#pragma mark - init method

- (void)setUpView {
    [self initView];
    [self initData];
    [self addNotifications];
}

- (void)initView {
    
    self.baseNavView.navTitleLabel.text = @"举报商家";
    
    self.view.backgroundColor = mBackgroudColor;
    CGFloat kTableViewHeight = KScreenHeight - TJ_NavBarHeight;
    self.tableView.height = kTableViewHeight;
    self.tableView.mj_y = self.baseNavView.bottom;
}

- (void)initData {
    
}


#pragma mark - tableview delegate/dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (section == 0) {
        return self.model.questions.count;
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 52;
    }else if (indexPath.section == 1){
        return 34;
    }else if (indexPath.section ==2){
        return 251;
    }else if (indexPath.section == 3){
        return 10;
    }
    return 54;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.imageView.image = indexPath.row == self.model.currentIndex
                                ?[UIImage imageNamed:@"meat_complaints_selected"]
                                :[UIImage imageNamed:@"meat_complaints_unselected"];
        cell.textLabel.text = self.model.questions[indexPath.row];
        cell.textLabel.textColor = UIColorFromRGB(0x363636);
        cell.textLabel.font = mFont(16);
        return cell;
    }else if (indexPath.section == 1){
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell_section" forIndexPath:indexPath];
        cell.textLabel.text = @"请输入您的问题或照片";
        cell.textLabel.textColor = UIColorFromRGB(0x969696);
        cell.textLabel.font = mFont(14);
        cell.backgroundColor = mBackgroudColor;
        return cell;
    }else if (indexPath.section == 2){
       
        MeatComplaintCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ComplaintBusinessCustomCell"];
        cell.model = self.model;
        
        kWeakSelf(self);
        cell.dealPhotoBlock = ^(NSInteger index, DealPhotoOperation operation) {
            
            if (operation == DealPhotoOperation_Add) {
                [weakself addPhotoOperationByTableView:tableView];
            }else{
                [weakself.model.photos removeObjectAtIndex:index];
                [weakself localReloadTableViewBySection:2];
            }
            [weakself checkUpdateDataIsWhole];
        };
                
        return cell;
        
    }else if(indexPath.section == 3){
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell_sectionLittle" forIndexPath:indexPath];
        cell.backgroundColor = mBackgroudColor;
        return cell;
    }
    
    MeatComplaintIphoneCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ComplaintBusinessIphoneCell"];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        self.model.currentIndex = indexPath.row;
        self.model.content = self.model.questions[indexPath.row];
        [self localReloadTableViewBySection:0];
        [self checkUpdateDataIsWhole];
    }
}


#pragma mark - UIImagePicker Delegate

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = info[UIImagePickerControllerEditedImage];
    if (!image) {
        NSLog(@"获取头像照片失败");
    }else {
        [self.model.photos addObject:image];
        [self localReloadTableViewBySection:2];
        [self checkUpdateDataIsWhole];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - target action

- (void)submitQuestion{
    
    if (self.model.isSumbit) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定取消举报？" message:@"取消举报，当前信息不会被保留。" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [cancelAction setValue:UIColorFromRGB(0x363636) forKey:@"titleTextColor"];
        
        kWeakSelf(self);
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            MeatComplationSuccessViewController *vc = [[MeatComplationSuccessViewController alloc] init];
            [weakself.navigationController pushViewController:vc animated:YES];
        }];
        [okAction setValue:mMainColor forKey:@"titleTextColor"];
        
        
        [alert addAction:cancelAction];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        NSLog(@"请重新输入");
    }
}


//跳转相册
- (void)addPhotoOperationByTableView:(UITableView *)tableView{
    //修改头像
    [tableView endEditing:YES];
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    kWeakSelf(self)
    UIAlertAction * cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself presentViewController:weakself.imagePicker animated:YES completion:nil];
    }];
    UIAlertAction * photosAction = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.allowsEditing = YES;
        [weakself presentViewController:picker animated:YES completion:nil];
    }];
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:cameraAction];
    [alert addAction:photosAction];
    [alert addAction:cancelAction];
    [weakself presentViewController:alert animated:YES completion:nil];
}

//检测数据
- (void)checkUpdateDataIsWhole{
    if (
        ![self isBlankString:self.model.content]
        &&![self isBlankString:self.model.phone]
        )
    {
        self.model.isSumbit = YES;
    }else{
        self.model.isSumbit = NO;
    }
}

#pragma mark - setter and getter

- (void)registerTableViewCell{
    
    self.tableView.separatorColor = UIColorFromRGB(0xF2F2F2);
    self.tableView.tableHeaderView = self.tipView;
    self.tableView.tableFooterView = self.footer;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell_section"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell_sectionLittle"];
    [self.tableView registerClass:[MeatComplaintCustomCell class] forCellReuseIdentifier:@"ComplaintBusinessCustomCell"];
    [self.tableView registerClass:[MeatComplaintIphoneCell class] forCellReuseIdentifier:@"ComplaintBusinessIphoneCell"];
}


- (UIView *)tipView{
    if (!_tipView) {
        _tipView = [[UIView alloc] init];
        _tipView.frame = CGRectMake(0, 0, KScreenWidth, 58);
        _tipView.backgroundColor = UIColorFromRGB(0xFFF9D4);
        
        NSString *contentStr = @"发现对方有违规交易、不良行为等可进行投诉，豚集不会对外披露您的真实姓名，请放心提交。在线客服 ";
        YYLabel *tipLab = [YYLabel new];
        tipLab.numberOfLines = 0;
        NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]initWithString:contentStr];
        
        [attr yy_setAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xF25C62) range:[contentStr rangeOfString:@"在线客服 "]];
        [attr yy_setAttribute:NSFontAttributeName value:mFont(12) range:NSMakeRange(0, contentStr.length)];
        
        [attr yy_setAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xEC8C00) range:NSMakeRange(0, contentStr.length - 5)];
        
        /**点击富文本，服务协议和法律声明的跳转*/
        @weakify(self);
        [attr yy_setTextHighlightRange:NSMakeRange(contentStr.length - 5, 5) color:UIColorFromRGB(0xF25C62) backgroundColor:UIColorFromRGB(0xFFF9D4) tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
            NSLog(@"点击的是---");
        }];
        
        YYAnimatedImageView *imageView2= [[YYAnimatedImageView alloc] initWithImage:[UIImage imageNamed:@"meat_complaints_arrow"]];
        imageView2.frame = CGRectMake(0, 0, 16, 16);
        
        NSMutableAttributedString *attachText2= [NSMutableAttributedString yy_attachmentStringWithContent:imageView2 contentMode:UIViewContentModeScaleAspectFit attachmentSize:imageView2.frame.size alignToFont:mFont(12) alignment:YYTextVerticalAlignmentCenter];
        
        [attr appendAttributedString:attachText2];
        
        attr.yy_lineSpacing = 5;
        tipLab.attributedText = attr;
        tipLab.frame = CGRectMake(15, 7, KScreenWidth - 30, 44);
        [_tipView addSubview:tipLab];
    }
    return _tipView;
}

- (UIView *)footer{
    if (!_footer) {
        _footer = [[UIView alloc] init];
        _footer.backgroundColor = mBackgroudColor;
        _footer.frame = CGRectMake(0, 0, KScreenWidth, 148);
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"提交举报" forState:UIControlStateNormal];
        [button setTitleColor:KWhiteColor forState:UIControlStateNormal];
        button.titleLabel.font = mMediumFont(16);
        UIImageView *bg = [[UIImageView alloc] init];
        bg.image = [UIImage imageNamed:@"meat_shop_sumbit_bg"];
        bg.frame = CGRectMake(0, 0, KScreenWidth - 30, 48);
        [button insertSubview:bg atIndex:0];
        button.frame = CGRectMake(15, 50, KScreenWidth -30, 48);
        [button addTarget:self action:@selector(submitQuestion) forControlEvents:UIControlEventTouchUpInside];
        [_footer addSubview:button];
    }
    return _footer;
}

- (UIImagePickerController *)imagePicker
{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc]init];
        _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        _imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        _imagePicker.allowsEditing = YES;
        _imagePicker.delegate = self;
    }
    return _imagePicker;
}

- (MeatComplaintModel *)model{
    if (!_model) {
        _model = [[MeatComplaintModel alloc] init];
    }
    return _model;
}

#pragma mark - other methods

- (void)textViewDidChanged:(NSNotification *)notification
{
    UITextView *textView = notification.object;
    self.model.content = textView.text;
}

- (void)textFieldDidChanged:(NSNotification *)notification
{
    UITextField *textField = notification.object;
    self.model.phone = textField.text;
}

- (void)keyboardDidShow:(NSNotification *)notification{
    NSDictionary *info = [notification userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    kWeakSelf(self);
    [UIView animateWithDuration:duration animations:^{
        weakself.tableView.mj_y = 0;
    }];
    
    //当键盘升起的时候添加点击降落操作
    if (!self.tap) {
        self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    }
    [self.view addGestureRecognizer:self.tap];
}

//取消键盘响应
- (void)hideKeyboard{
    
    [self.view endEditing:YES];
}


- (void)keyboardWillHidden:(NSNotification *)notification{
    
    self.tableView.mj_y = 0;
    if (self.tap) {
        [self.view removeGestureRecognizer:self.tap];
    }
}

- (void)addNotifications{
    
   [kNotificationCenter addObserver:self selector:@selector(textViewDidChanged:) name:UITextViewTextDidChangeNotification object:nil];
   [kNotificationCenter addObserver:self selector:@selector(textFieldDidChanged:) name:UITextFieldTextDidChangeNotification object:nil];
   [kNotificationCenter addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardWillShowNotification object:nil];
   [kNotificationCenter addObserver:self selector:@selector(keyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)removeNotifications{
    
    [kNotificationCenter removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
    [kNotificationCenter removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
    [kNotificationCenter removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [kNotificationCenter removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)dealloc
{
    [self removeNotifications];
}


@end
